package com.taxi.driver.module.order.detail;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.qianxx.utils.PhoneUtils;
import com.qianxx.view.HeadView;
import com.taxi.driver.R;
import com.taxi.driver.common.AppConfig;
import com.taxi.driver.common.BaseFragment;
import com.taxi.driver.config.DriverType;
import com.taxi.driver.config.IConstants;
import com.taxi.driver.config.OrderStatus;
import com.taxi.driver.config.TimeType;
import com.taxi.driver.data.user.UserRepository;
import com.taxi.driver.event.MapEvent;
import com.taxi.driver.module.order.cancel.OrderCancelActivity;
import com.taxi.driver.module.order.complain.OrderComplainActivity;
import com.taxi.driver.module.order.detail.dagger.DaggerOrderDetailComponent;
import com.taxi.driver.module.order.detail.dagger.OrderDetailModule;
import com.taxi.driver.module.order.pay.OrderPayActivity;
import com.taxi.driver.module.order.price.PriceCheckActivity;
import com.taxi.driver.module.order.price.PriceDetailActivity;
import com.taxi.driver.module.order.price.PriceInputActivity;
import com.taxi.driver.module.vo.OrderSummaryVO;
import com.taxi.driver.module.vo.OrderVO;
import com.taxi.driver.socket.SocketEvent;
import com.taxi.driver.socket.SocketPushContent;
import com.taxi.driver.util.Navigate;
import com.taxi.driver.util.SpeechUtil;
import com.taxi.driver.widget.CircleImageView;
import com.taxi.driver.widget.ImageViewPlus;
import com.taxi.driver.widget.TextViewPlus;
import com.taxi.driver.widget.dialog.ConfirmDialog;
import com.taxi.driver.widget.dialog.TwoSelectorDialog;

import org.greenrobot.eventbus.EventBus;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 功能描述：订单详情页面
 */
public class OrderDetailFragment extends BaseFragment implements OrderDetailContract.View {

    private final int HELP = 1; //客服
    private final int COMPLAIN = 2; //投诉
    private final int CANCEL = 3; //取消订单
    private final int REMIND = 4; //催款
    private final int CASH = 5; //收现
    @BindView(R.id.head_view)
    HeadView mHeadView;
    @BindView(R.id.iv_avatar)
    CircleImageView mIvAvatar;
    @BindView(R.id.tv_order_no)
    TextView mTvOrderNo;
    @BindView(R.id.tv_info)
    TextView mTvInfo;
    @BindView(R.id.tv_time)
    TextViewPlus mTvTime;
    @BindView(R.id.tv_type)
    TextView mTvType;
    @BindView(R.id.tv_status)
    TextView mTvStatus;
    @BindView(R.id.tv_start)
    TextViewPlus mTvStart;
    @BindView(R.id.tv_end)
    TextViewPlus mTvEnd;
    @BindView(R.id.tv_price)
    TextView mTvPrice;
    @BindView(R.id.ll_price)
    LinearLayout mLlPrice;
    @BindView(R.id.tvTag1)
    TextView mTvTag1;
    @BindView(R.id.divider1)
    View mDivider1;
    @BindView(R.id.tvTag2)
    TextView mTvTag2;
    @BindView(R.id.divider2)
    View mDivider2;
    @BindView(R.id.tvTag3)
    TextView mTvTag3;
    @BindView(R.id.divider3)
    View mDivider3;
    @BindView(R.id.tvTag4)
    TextView mTvTag4;
    @BindView(R.id.tv_continue)
    TextView mTvContinue;
    @BindView(R.id.tv_begin)
    TextView mTvBegin;
    @BindView(R.id.layout_detail)
    LinearLayout mLayoutDetail;
    @BindView(R.id.iv_phone)
    ImageViewPlus  iv_call;
    @Inject
    OrderDetailPresenter mPresenter;
    @Inject
    UserRepository mUserRepository;

    NetworkChangeReceiver mReceiver;
    String strStatus = "";
//    String stat="";
    double mTotalFare;//总费用
    private ConfirmDialog cancelDialog, reassignDialog;
    private TwoSelectorDialog payComifgDialog;
    private int value;//标记是从哪个页面过来的  肖利

    //    private String mCurrentCity;
    public static OrderDetailFragment newInstance(String orderUuid, boolean refresh,int status) {
        OrderDetailFragment fragment = new OrderDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putString(IConstants.ORDER_UUID, orderUuid);
        bundle.putBoolean(IConstants.REFRESH, refresh);
        bundle.putInt("status",status);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_order_detail, container, false);
        ButterKnife.bind(this, mView);
        initTag(); //初始化按键，设置整型标签
        mPresenter.onCreate();
        mPresenter.setOrderUuid(getArguments().getString(IConstants.ORDER_UUID)); //设置订单编号
//        mPresenter.getCurrentCity();
        boolean refresh = getArguments().getBoolean(IConstants.REFRESH, false);
        value = getArguments().getInt("status",0);
//        KLog.e("=-=-=-=-000"+String.valueOf(getArguments().getInt("status",0)));
        if (refresh) mPresenter.setOrderRefresh();
        register();
        return mView;
    }
    private void initTag() {
        mTvTag1.setTag(0);
        mTvTag2.setTag(0);
        mTvTag3.setTag(0);
        mTvTag4.setTag(0);
        if (String.valueOf(getArguments().getInt("status",0)).equals("90210")){
            iv_call.setVisibility(View.INVISIBLE);
        }

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        DaggerOrderDetailComponent.builder()
                .appComponent(getAppComponent())
                .orderDetailModule(new OrderDetailModule(this))
                .build().inject(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.subscribe();
    }

    @Override
    public void onPause() {
        super.onPause();
        mPresenter.unsubscribe();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresenter.onDestory();
        unregister();
    }

    @OnClick({R.id.iv_phone, R.id.tv_price, R.id.tv_price_detail, R.id.tvTag1, R.id.tvTag2, R.id.tvTag3, R.id.tvTag4, R.id.tv_continue, R.id.tv_begin})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_phone: //跳转拨号盘
                if (!strStatus.equals("已取消")){
                    PhoneUtils.skip(getContext(), mPresenter.getPassengerPhone());
//                    iv_call.setSelected(false);
//                    iv_call.setClickable(false);
                }
                break;
            case R.id.tv_price:
            case R.id.tv_price_detail: // 展示费用明细
                PriceDetailActivity.actionStart(getContext(), mPresenter.getOrderUuid(), mPresenter.getOrderCostEntity());
                break;
            case R.id.tvTag1:
            case R.id.tvTag2:
            case R.id.tvTag3:
            case R.id.tvTag4:

                dealwithTag((int) view.getTag());
                break;
            case R.id.tv_continue: //继续行程
                // 说明："进行中订单页"的加载模式设置为了SingleTask，直接跳转过去即可
                SpeechUtil.speech(getActivity(), "继续行程");
                Navigate.openOrderOngoing(getContext(), mPresenter.getOrderUuid());
                break;
            case R.id.tv_begin: //出发去接乘客（确认弹窗）
                showBeginConfirm();
                break;
        }
    }

 /*   @Override
    public void getCurrentCity(String city) {
        mCurrentCity=city;
    }*/

    /**
     * 设置页面显示
     *
     * @param vo
     */
    @Override
    public void setOrderInfo(OrderVO vo) {
        if (value==110&&vo.subStatus==OrderStatus.WAIT_ARRIVE_ORIGIN)  mHeadView.getLeftView().setVisibility(View.GONE);//如果是实时单过来的返回键禁用
        //显示乘客头像
        if (vo.passenger != null && !TextUtils.isEmpty(vo.passenger.face)) {
            Glide.with(getContext())
                    .load(vo.passenger.face)
                    .into(mIvAvatar);
        }

        int resId = OrderSummaryVO.tripType(vo.typeTripNew, vo.typeTimeNew);
        if (resId == 0) {
            mTvType.setVisibility(View.GONE);
        } else {
            mTvType.setText(resId);
            mTvType.setVisibility(View.VISIBLE);
        }

        if (!TextUtils.isEmpty(vo.orderNo)) {
            mTvOrderNo.setVisibility(View.VISIBLE);
            mTvOrderNo.setText(getString(R.string.the_order_no, vo.orderNo));
        } else {
            mTvOrderNo.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(vo.actualPasMob)) {
            mTvInfo.setText(TextUtils.isEmpty(vo.getActualPasMobEnd()) ?
                    "" : "尾号" + vo.getActualPasMobEnd());//换乘车人电话尾号
        } else {
            mTvInfo.setText(TextUtils.isEmpty(vo.getPassengerPhoneEnd()) ?
                    "" : "尾号" + vo.getPassengerPhoneEnd());//发单本人电话尾号
        }

        mTvTime.setText(vo.getStrDepartTime());//显示订单时间
        mTvStart.setText(vo.originAddress);//出发地
        mTvEnd.setText(vo.destAddress);//目的地

        if (vo.mainStatus == null || vo.subStatus == null) {
            toast("订单状态异常");
            return;
        }
        /* 根据订单状态，设置不同的显示 */
        int btnCount = 2;
        boolean highLight = false;
        int tvContinueVis = View.GONE;
        int tvBeginVis = View.GONE;
        boolean needPriceInput = false; //是否需要跳转到费用输入页(出租车业务)
        boolean needPriceCheck = false; //是否需要跳转费用确认页(专车业务)
        switch (vo.mainStatus) {//订单主状态
            case OrderStatus.ORDER_MAIN_STATUS_CANCEL: //订单取消（完结）
                strStatus = "已取消";
                break;
            case OrderStatus.ORDER_MAIN_STATUS_PAYED: //支付完成、订单结束
                strStatus = "已支付";
                break;
            case OrderStatus.ORDER_MAIN_STATUS_DONE: //行程结束、待支付
                strStatus = "未支付";
                highLight = true;
                btnCount = 4;
                break;
            default:
                if (value == 110&&vo.subStatus==OrderStatus.WAIT_ARRIVE_ORIGIN)  {
                    strStatus = "未开始";
                    highLight = true;
                    tvBeginVis = View.VISIBLE; //显示"出发去接乘客"的按钮
                    break;
                }
                switch (vo.subStatus) {//订单子状态
                    case OrderStatus.WAIT_BEGIN_APPOINTMENT ://等待接驾
                        strStatus = "未开始";
                        highLight = true;
                        tvBeginVis = View.VISIBLE; //显示"出发去接乘客"的按钮
                        break;
                    case OrderStatus.WAIT_PASSENGER_GET_ON://司机已到达"上车地点"，但乘客未上车
                        strStatus = "进行中";
                        highLight = true;
                        tvContinueVis = View.VISIBLE; //显示"继续行程"的按钮
                        btnCount = 3; //"司机到达上车地点"且"乘客还未上车"前，可以取消订单
                        break;
                    case OrderStatus.WAIT_ARRIVE_ORIGIN://司机已出发，但未到达"上车地点"
                    case OrderStatus.DEPART://行程中(乘客已上车)
                        strStatus = "进行中";
                        highLight = true;
                        tvContinueVis = View.VISIBLE; //显示"继续行程"的按钮
                        break;
                    case OrderStatus.ARRIVE_DEST://到达目的地
                        strStatus = "未支付";
                        highLight = true;
                        btnCount = 4;
                        if (AppConfig.isTaxi()) needPriceInput = true; //出租车，需要输入金额
                        if (AppConfig.isSpecial()) needPriceCheck = true; //专车，需要确认费用
                        break;
                }
                break;
        }
        showTvTag(btnCount, vo);
        mTvStatus.setText(strStatus);
        mTvStatus.setSelected(highLight);
        mTvContinue.setVisibility(tvContinueVis);
        mTvBegin.setVisibility(tvBeginVis);
        if ( mPresenter.driverType() == DriverType.SPECIAL) {
            mTvBegin.setText(R.string.order_begin);
        }

        // 是否显示费用
        if (vo.totalFare == null) {
            mLlPrice.setVisibility(View.GONE);
        } else {
            if (vo.mainStatus == OrderStatus.ORDER_MAIN_STATUS_CANCEL && vo.totalFare == 0d) {
                mLlPrice.setVisibility(View.GONE);
            } else {
                showTotalFare(vo.totalFare);
            }
        }

        // 是否需要跳转费用输入页
        if (needPriceInput)
            PriceInputActivity.actionStart(getContext(), mPresenter.getOrderUuid(), mPresenter.getPassengerVO());
        // 是否需要跳转费用确认页
        if (needPriceCheck)
            PriceCheckActivity.actionStart((OrderDetailActivity) getActivity(), mPresenter.getOrderUuid(), mPresenter.getPassengerVO());

        if (vo.typeTime == TimeType.DAILY_RENT || vo.typeTime == TimeType.HALF_DAY_RENT) { //订单类型是日租/半日租
            if (vo.mainStatus == OrderStatus.ORDER_MAIN_STATUS_PAYED ||
                    vo.mainStatus == OrderStatus.ORDER_MAIN_STATUS_DONE) {//完成行程已支付/完成行程未支付
                //显示起点和终点
                EventBus.getDefault().post(new MapEvent(MapEvent.MAP_ORIGN_DEST,
                        vo.getOriginLatLng(), vo.getDestLatLng(), mLayoutDetail.getHeight()));
            } else {
                //只显示起点
                EventBus.getDefault().post(new MapEvent(MapEvent.MAP_POINT, vo.getOriginLatLng()));
            }
        } else {//其余订单类型
            //显示订单起点到终点的规划路径
            EventBus.getDefault().post(new MapEvent(MapEvent.MAP_CACULATE_ROUTE,
                    vo.getOriginLatLng(), vo.getDestLatLng(), TimeType.APPOINTMENT, mPresenter.driverType()));

            new Handler().postDelayed(() ->
                    EventBus.getDefault().post(new MapEvent(MapEvent.MAP_PADDING, 0, mLayoutDetail.getHeight())), 200);
        }
    }

    /**
     * 显示总费用
     *
     * @param totalFare
     */
    @Override
    public void showTotalFare(double totalFare) {
        mTotalFare = totalFare;
        mLlPrice.setVisibility(View.VISIBLE);
        mTvPrice.setText(String.format("%.01f", totalFare) + "元");
    }

    /**
     * 显示“出发去接乘客”的弹窗
     */
    @Override
    public void showBeginConfirm() {
        String title = null;
        if (mPresenter.driverType() == DriverType.SPECIAL) {
            title = "现在出发去接乘客吗？";
        }
        new TwoSelectorDialog(getActivity(), title, null, "取消", "确定")
                .setConfirmClickListener(dialog -> {
                    dialog.dismiss();
                    if (value==110) {
                        orderBeginSuccess(mPresenter.getOrderUuid());
                    }else {
                        mPresenter.reqOrderBegin();
                    }

                }).setCancelClickListener(Dialog::dismiss).show();
    }

    /**
     * 跳转到行程中页面
     * @param orderUuid
     */
    @Override
    public void orderBeginSuccess(String orderUuid) {
        Navigate.openOrderOngoing(getContext(), orderUuid);
        getActivity().finish();
    }

    /**
     * 显示收现提示弹窗
     */
    @Override
    public void showPayConfirm() {
            if (payComifgDialog != null)
                payComifgDialog.dismiss();

            String title = "";
            if ( mPresenter.driverType() == DriverType.SPECIAL
                    ) {
                title = "确认已收到乘客支付的现金？";
            }
            payComifgDialog = new TwoSelectorDialog(getActivity(), "提醒", title, "取消", "确认");
            payComifgDialog.setConfirmClickListener(sweetAlertDialog ->
            {
                if (payComifgDialog != null)
                    payComifgDialog.dismiss();
                OrderPayActivity.actionStart(getContext(), mPresenter.getOrderUuid(), mTotalFare);
            }).setCancelClickListener(sweetAlertDialog ->
            {
                if (payComifgDialog != null)
                    payComifgDialog.dismiss();
            });
            payComifgDialog.show();

    }

    /**
     * 显示后台取消订单的弹窗
     *
     * @param push
     */
    @Override
    public void showCancelDialog(SocketPushContent push) {
        if (cancelDialog == null) {
            cancelDialog = new ConfirmDialog(getActivity(), push.data.title, push.data.content, "确认");
            cancelDialog.setConfirmClickListener(sweetAlertDialog ->
            {
                mPresenter.reqOrderDetail(true);
                if (cancelDialog != null)
                    cancelDialog.dismiss();
            });
            cancelDialog.show();
        }
    }

    /**
     * 显示订单改派的弹窗
     *
     * @param push
     */
    @Override
    public void showReassignDialog(SocketPushContent push) {
        if (reassignDialog == null) {
            reassignDialog = new ConfirmDialog(getActivity(), push.data.title, push.data.content, "确认");
            reassignDialog.setConfirmClickListener(sweetAlertDialog ->
            {
                if (reassignDialog != null)
                    reassignDialog.dismiss();
                getActivity().finish();
            });
            reassignDialog.show();
        }
    }

    @Override
    public void closeDialog() {
        if (payComifgDialog != null)
            payComifgDialog.dismiss();
    }

    @Override
    public void showReassignedDialog(String msg) {
        if (reassignDialog == null) {
            reassignDialog = new ConfirmDialog(getActivity(), msg, null, "确认");
            reassignDialog.setConfirmClickListener(sweetAlertDialog ->
            {
                if (reassignDialog != null)
                    reassignDialog.dismiss();
                getActivity().finish();
            });
            reassignDialog.show();
        }
    }


    /**
     * 标签按钮对应的点击事件
     *
     * @param tag
     */
    private void dealwithTag(int tag) {
        switch (tag) {
            case HELP: //客服
                PhoneUtils.skip(getContext(), R.string.contact_phone);
//                if (mCurrentCity.equals("天津市")){
//                    PhoneUtils.skip(getContext(), R.string.contact_phone_tianjing);
//                }else{
//                    PhoneUtils.skip(getContext(), R.string.contact_phone_other);
//                }
                break;
            case COMPLAIN: //投诉
                OrderComplainActivity.actionStart(getContext(), mPresenter.getOrderUuid());
                break;
            case CANCEL: //取消订单
                OrderCancelActivity.actionStart(getContext(), mPresenter.getOrderUuid());
                break;
            case REMIND: //催款
                mPresenter.rushFare();
                break;
            case CASH: //收现
                showPayConfirm();
                break;
        }
    }

    /**
     * 设置标签按钮的显示
     * 目前有的几种显示：2、3、4
     *
     * @param count
     */
    private void showTvTag(int count, OrderVO vo) {
        // mTvTag1 需设置"可点击"和"不可点击"两种状态
        boolean isEnable = true;
        switch (count) {
            case 3:
                visible(mTvTag1, mDivider1, mTvTag2, mDivider2, mTvTag3);
                gone(mDivider3, mTvTag4);
                mTvTag1.setTag(HELP);
                mTvTag1.setText(R.string.order_detail_btn_help);
                mTvTag2.setTag(COMPLAIN);
                mTvTag2.setText(R.string.order_detail_btn_complain);
                mTvTag3.setTag(CANCEL);
                mTvTag3.setText(R.string.order_detail_btn_cancel);
                break;
            case 4:
                visible(mTvTag1, mDivider1, mTvTag2, mDivider2, mTvTag3, mDivider3, mTvTag4);
                mTvTag1.setTag(REMIND);
                mTvTag1.setText(R.string.order_detail_btn_remind);
//                isEnable = (vo.canHurryPay != null && vo.canHurryPay == 1);
                isEnable = false;//设置按钮一直不可点击

                    mTvTag2.setTag(CASH);
                    mTvTag2.setText(R.string.order_detail_btn_cash);

                mTvTag3.setTag(COMPLAIN);
                mTvTag3.setText(R.string.order_detail_btn_complain);
                mTvTag4.setTag(HELP);
                mTvTag4.setText(R.string.order_detail_btn_help);
                break;
            default:
                visible(mTvTag1, mDivider1, mTvTag2);
                gone(mDivider2, mTvTag3, mDivider3, mTvTag4);
                mTvTag1.setTag(HELP);
                mTvTag1.setText(R.string.order_detail_btn_help);
                mTvTag2.setTag(COMPLAIN);
                mTvTag2.setText(R.string.order_detail_btn_complain);
                break;
        }
        mTvTag1.setEnabled(isEnable);
        mTvTag2.setEnabled(isEnable);//收现按钮不可点击
    }

    /**
     * 注册网络监听广播
     */
    public void register() {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        mReceiver = new NetworkChangeReceiver();
        getActivity().registerReceiver(mReceiver, filter);
    }

    /**
     * 注销网络监听广播
     */
    public void unregister() {
        getActivity().unregisterReceiver(mReceiver);
    }

    /**
     * 监听网络变化的广播
     */
    private class NetworkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //网络从断开到恢复时，重新获取订单详情
            checkNetwork();
        }
    }

    /**
     * 检查网络状态
     */
    private void checkNetwork() {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        boolean networkAvailable = networkInfo != null && networkInfo.isAvailable();
        mUserRepository.setNetworkStatus(!networkAvailable);
        if (networkAvailable) {
            EventBus.getDefault().post(new SocketEvent(SocketEvent.CONNECT));
        } else {
            EventBus.getDefault().post(new SocketEvent(SocketEvent.DISCONNECT));
        }
    }

}
